package com.youngcms.controller.admin;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.youngcms.bean.Dict;
import com.youngcms.bean.DictType;
import com.youngcms.controller.base.AdminBaseController;
import com.youngcms.service.DictService;
import com.youngcms.service.DictTypeService;
import com.youngcms.vo.ActionResult;
import com.youngcms.vo.QueryResult;
@Controller
@RequestMapping("/admin/dict/")
@SessionAttributes("pageForm")
public class DictController extends AdminBaseController{

     @Autowired
     private DictService dictService;
     @Autowired
     private DictTypeService dictTypeService;

     @RequestMapping("list")
     public ModelAndView list(Dict dict,HttpServletRequest request) throws Exception{
        QueryResult<Dict> queryResult=dictService.list(dict);
        dict.setPageDate(queryResult.getQueryResult());
        dict.setTotalCount(queryResult.getCount());
        ModelAndView mnv = new ModelAndView();
        mnv.addObject(DEFAULT_PAGE_VIEW,dict);
        mnv.setViewName("view/admin/dict/list");
        return mnv;
     }

     @RequestMapping("delete")
     @ResponseBody
     public ActionResult delete(Dict dict,HttpServletRequest request) throws Exception{
        ActionResult result=new ActionResult();
       try {
	     dictService.deleteByPrimaryKey(dict.getId());
	     result.setSuccess(true);
	     result.setMessage(RESULE_SUCCESS_DELETE);
		 } catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(RESULE_ERROR_DELETE);
		}
		return result;
	 }

	 @RequestMapping("showForm")
	 public ModelAndView addForm(Dict dict,HttpServletRequest request) throws Exception{
		ModelAndView mnv = new ModelAndView();
		QueryResult<DictType> result=dictTypeService.list();
		if(dict.getId()!=null){
			dict=dictService.selectByPrimaryKey(dict.getId());
		}
		mnv.addObject("DICT_TYPE_LIST", result.getQueryResult());
		mnv.addObject(DEFAULT_PAGE_FORM, dict);
		mnv.setViewName("view/admin/dict/form");
		return mnv;
	 }

	@RequestMapping("addOrUpdate")
	@ResponseBody
	public ActionResult add(Dict dict,HttpServletRequest request) throws Exception{
		ActionResult result=new ActionResult();
		try {
			String dict_type_id=request.getParameter("dict_type_id");
			if(StringUtils.isNotBlank(dict_type_id)){
				dict.setDictTypeId(Integer.valueOf(dict_type_id));
			}
			dictService.saveOrUpdate(dict);
			result.setSuccess(true);
			result.setMessage(RESULE_SUCCESS);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage(RESULE_ERROR);
		}
		return result;
	}
}
